package com.sphd.beautysalon.model;


import com.android.volley.VolleyError;
import com.sphd.beautysalon.info.LoginInfo;
import com.sphd.beautysalon.interfaces.VolleyJsonObjectCallBack;
import com.sphd.beautysalon.presenter.LoginPresenterImpl;
import com.wzh.frame.utils.JsonUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

/**
 * Created by Hu on 2016/10/27
 */

public class LoginModelImpl implements LoginModel, VolleyJsonObjectCallBack {
    LoginPresenterImpl loginPresenter;

    @Override
    public void sendUrl(String url, LoginPresenterImpl loginPresenter) {
        this.loginPresenter = loginPresenter;
        volleyUtil.setJsonObjectRequest(url, this);
    }

    @Override
    public void onResponse(JSONObject response) {
        try {
            List<LoginInfo> loginInfos = JsonUtil.getListFromString(response.getString("res"), LoginInfo.class);
            if (loginInfos.size() != 0) {
                LoginInfo loginInfo = loginInfos.get(0);

//            LoginInfo loginInfo = JsonUtil.getObjectFromString(response.getString("res"), LoginInfo.class);
                if (response.has("cgnumber")) {
                    int cgnumber = response.getInt("cgnumber");
                    loginPresenter.sendCgNo(cgnumber);
                    loginInfo.setCgnumber(cgnumber);
                }
                if (response.has("underlingcgid")) {
                    int underlingcgid = response.getInt("underlingcgid");
                    loginInfo.setUnderlingcgid(underlingcgid);
                    loginPresenter.sendLcgid(underlingcgid);
                }

                loginPresenter.sendRes(loginInfo);
            }else {
                loginPresenter.sendPwdError();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onErrorResponse(VolleyError error) {
        loginPresenter.sendError(error);
    }
}